package com.af.monitorModule.generator.service.impl;

import com.af.monitorModule.common.ResultEnum;
import com.af.monitorModule.generator.entity.TimedTask;
import com.af.monitorModule.generator.mapper.TimedTaskMapper;
import com.af.monitorModule.generator.service.TimedTaskService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyz_4dou
 * @since 2021-03-02
 */
@Service
public class TimedTaskServiceImpl extends ServiceImpl<TimedTaskMapper, TimedTask> implements TimedTaskService {

    @Autowired
    private TimedTaskMapper timedTaskMapper;

    @Autowired
    private HashOperations<String, String, Object> hashOperations;

    @Override
    public JSONObject getRunTask(String monitor) {
        JSONObject res = new JSONObject();
        try {
            //查询数据库中应该执行的任务
            List<TimedTask> run = timedTaskMapper.getRun(Integer.valueOf(monitor));
            //查询在界面上点击过的立即执行的任务
            List<TimedTask> all = timedTaskMapper.getAll(Integer.valueOf(monitor));
            all.forEach( oneJob -> {
                if(hashOperations.hasKey("runNow",oneJob.getId().toString())){
                    run.add(timedTaskMapper.selectById(oneJob.getId()).setRunNow(true));
                    hashOperations.delete("runNow",oneJob.getId().toString());
                }
            });
            res.put("code", 200);
            res.put("data", run);
        } catch (Exception e) {
            res = ResultEnum.UNKOWN_ERROR.getResult();
        }
        return res;
    }

    @Override
    public String sendOver(String task) {
        if (task == null) {
            return ResultEnum.PARAM_INCORRECRT.getMsg();
        }
        TimedTask timedTask = timedTaskMapper.selectById(task);
        if (timedTask == null){
            return ResultEnum.DATA_ISNOT_EXIST.getMsg();
        }
        if (timedTask.getState() == 0){
            return ResultEnum.STATE_ERROR.getMsg();
        }
        timedTask.setTaskRunTime(timedTask.getTaskRunTime()
                .plusDays(timedTask.getTaskCycleDay())
                .plusHours(timedTask.getTaskCycleHour()));
        timedTaskMapper.updateById(timedTask);
        return ResultEnum.OK.getMsg();
    }

    @Override
    public JSONObject findTask(String page, String limit, JSONObject search) {
        Page<TimedTask> p = new Page<TimedTask>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<TimedTask> wrapper = new QueryWrapper<>();
        if (search != null)
            search.forEach((k,v)->{
                if (!"".equals(v.toString().trim())){
                    switchParam(k,v.toString(),wrapper);
                }
            });
        timedTaskMapper.findTask(p,wrapper);
        JSONObject res = new JSONObject();
        res.put("data",p.getRecords());
        res.put("code",0);
        res.put("count",p.getTotal());
        res.put("msg","任务列表");
        return res;
    }

    @Override
    public JSONObject changeState(String id) {
        TimedTask timedTask = timedTaskMapper.selectById(id);
        if (timedTask == null){
            return ResultEnum.DATA_ISNOT_EXIST.getResult();
        }
        timedTask.setState(timedTask.getState() == 0 ? 1: 0);
        timedTaskMapper.updateById(timedTask);
        return ResultEnum.OK.getResult();
    }

    @Override
    public JSONObject batchStop(JSONObject ids) {
        if (ids == null){
            return ResultEnum.PARAM_INCORRECRT.getResult();
        }
        JSONArray ids1 = ids.getJSONArray("ids");
        StringBuffer stringBuffer = new StringBuffer();
        ids1.forEach((v)->{
            stringBuffer.append(","+v);
        });
        timedTaskMapper.stopBatch("(" + stringBuffer.toString().substring(1) + ")");
        return ResultEnum.OK.getResult();
    }

    @Override
    public JSONObject addTask(TimedTask timedTask) {
        if (timedTask == null){
            return ResultEnum.PARAM_INCORRECRT.getResult();
        }
        timedTask.setState(1);
        timedTaskMapper.insert(timedTask);
        return ResultEnum.OK.getResult();
    }

    @Override
    public JSONObject updateTask(TimedTask timedTask, String id) {
        if (timedTask == null || id == null){
            return ResultEnum.PARAM_INCORRECRT.getResult();
        }
        timedTask.setId(Integer.valueOf(id));
        timedTaskMapper.updateById(timedTask);
        return ResultEnum.OK.getResult();
    }

    @Override
    public JSONObject runNow(String id) {
        TimedTask timedTask = timedTaskMapper.selectById(id);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nextRunTime = timedTask.getTaskRunTime();
        LocalDateTime lastRunTime = nextRunTime.plusDays(-1 * timedTask.getTaskCycleDay()).plusHours(-1 * timedTask.getTaskCycleHour());
        //如果两分钟内将要执行 或 两分钟之前才执行过  则不允许设置立即执行
        if (now.plusMinutes(2).isAfter(nextRunTime) || lastRunTime.plusMinutes(2).isAfter(now)){
            return ResultEnum.CANT_RUN_NOW.getResult();
        }
        hashOperations.put("runNow",id,1);
        return ResultEnum.WILL_RUN_NOW.getResult();
    }


    public void switchParam(String key,String value ,QueryWrapper wrapper){
        switch (key){
            case "task_name":{
                wrapper.like("task_name",value);
                break;
            }
            default:{
                wrapper.eq(key,value);
                break;
            }
        }
    }
}
